﻿namespace vkUpploaderLib.HttpHelpers
{
    using System;
    using System.Windows.Forms;
    using Resourses;

    public class WebBrowserWindow : IDisposable
    {
        //WinControls, need to be disposed
        protected Form _form;
        protected WebBrowser _webBrowser;

        protected string _url;

        private bool _disposed;

        protected string _title;
        public WebBrowserNavigatedEventHandler NavigatedHandler;

        public WebBrowserWindow(string url) : this(url, StringResources.ProductName)
        {
            // do nothing
        }
        

        public WebBrowserWindow(string url, string formTitle)
        {
            _url = url;
            _title = formTitle;
           
        }

        protected void CreateControls()
        {
            _form = new Form();

            _webBrowser = new WebBrowser();
            _webBrowser.ScriptErrorsSuppressed = true;
            _webBrowser.Dock = DockStyle.Fill;

            _form.Controls.Add(_webBrowser);
            _form.Width = 800;
            _form.Height = 400;
            _form.Text = _title;
            _form.StartPosition = FormStartPosition.CenterScreen;
            _form.FormBorderStyle = FormBorderStyle.FixedDialog;
            _form.MaximizeBox = false;
            _form.ShowInTaskbar = false;

            _form.Shown += OnFormShown;

            if (NavigatedHandler != null)
                _webBrowser.Navigated += NavigatedHandler;

            _form.ShowDialog();
        }


        private void OnFormShown(object o, EventArgs args)
        {
            _webBrowser.Navigate(_url);
        }

      

        protected void DisposeControls()
        {
            Delegate[] clientList = NavigatedHandler.GetInvocationList();
            foreach (Delegate d in clientList)
                NavigatedHandler -= (d as WebBrowserNavigatedEventHandler);

            if (_webBrowser != null)
            {
                _webBrowser.Dispose();
                _webBrowser = null;
            }
            if (_form != null)
            {
                _form.Dispose();
                _form = null;
            }
            GC.Collect();
            _disposed = true;
        }

        ~WebBrowserWindow()
        {
            if (!_disposed)
            {
                DisposeControls();
            }
        }

        public void Dispose()
        {
            DisposeControls();
        }
    }
}